package com.mock.ems.controller;

import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.mock.base.util.CollectionUtil;
import com.mock.base.util.NumberUtil;
import com.mock.base.util.StringUtil;
import com.mock.ems.config.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 订单列表
 * @author whx
 * @date 2017/08/19
 */
public class ShopOrderController extends Controller {

    private static Map<String,String> statusMap = new HashMap<>();

    static{
        statusMap.put("awaiting_pay","待支付");
        statusMap.put("cancelled","取消");
        statusMap.put("payment_error","支付失败");
        statusMap.put("awaiting_ship","待发货");
        statusMap.put("shipped","已发货");
        statusMap.put("completed","订单完成");
    }

    public void index()  {
        renderJsp("/page/shoporder/shoporder_list.jsp");
    }

    public void pagination() {
        int limit = getParaToInt("limit");
        int offset = getParaToInt("offset");
        int pageNumber = (offset / limit) + 1;

        String selectSql = "select a.*,b.store_name_";
        StringBuilder sqlExceptSql = new StringBuilder(" from t_so_entity a inner join t_ou_shop b on a.shop_id_ = b.id_ where 1 = 1");
        List<Object> params = new ArrayList<Object>();

        String orderNo = getPara("so_no_", "");
        if (StringUtil.isNotEmpty(orderNo.trim())) {
            sqlExceptSql.append( " and a.so_no_ = ?");
            params.add(orderNo.trim());
        }

        String nickName = getPara("nick_name");
        if (StringUtil.isNotEmpty(nickName)) {
            List<Record> userRecordList = Db.find("select id from user where nick_name like ? ",'%' + nickName.trim() + '%');
            if (CollectionUtil.isNotEmpty(userRecordList)) {
                sqlExceptSql.append(" and a.create_by_ in ( ");
                userRecordList.stream().forEach(item -> {
                    sqlExceptSql.append("?,");
                    params.add(item.getLong("id"));
                });
                sqlExceptSql.deleteCharAt(sqlExceptSql.length() - 1);
                sqlExceptSql.append(") ");
            }
        }

        String storeName = getPara("store_name", "");
        if (StringUtil.isNotEmpty(storeName.trim())) {
            sqlExceptSql.append( " and b.store_name_ like ?");
            params.add("%" + storeName.trim() + "%");
        }

        Page<Record> recordList = Db.paginate(pageNumber, limit, selectSql, sqlExceptSql.toString(), params.toArray());
        if (CollectionUtil.isNotEmpty(recordList.getList())) {
            recordList.getList().forEach(item -> {
                Long userId = NumberUtil.toLong(item.getStr("create_by_"));
                Record user = UserManager.getUser(userId);
                if(user == null){
                    user = Db.findById("user",userId);
                    if(user != null){
                        UserManager.setUser(user);
                    }
                }
                item.set("nick_name",user == null ? "未知" : user.get("nick_name"));
            });
        }

        Map<String, Object> returnMap = new HashMap<String, Object>();
        returnMap.put("total", recordList.getTotalRow());
        returnMap.put("rows", recordList.getList());
        renderJson(returnMap);
    }

    public void info(){

        String id = getPara("id");
        Record record = Db.findById("t_so_entity","id_",id);
        if(record != null){

            Record shop = Db.findById("t_ou_shop","id_",record.getStr("shop_id_"));
            if(shop != null){
                shop.set("business_type_",shop.getStr("business_type_").equals("oto") ? "线下实体店"
                        : shop.getStr("business_type_").equals("online_store") ? "线上实体店" : "未知");
            }
            record.set("shop",shop);

            Record user = Db.findById("user",record.getStr("create_by_"));
            record.set("user",user);

            record.set("so_status_",statusMap.get(record.getStr("so_status_")));

            List<Record> productList = Db.find("select * from t_so_item where so_id_ = ?",id);
            if(CollectionUtil.isNotEmpty(productList)){
                productList.stream().forEach(product->{
                    String prodId = product.getStr("product_id_");
                    Record item = Db.findById("t_prod_entity","id_",prodId);
                    product.set("name",item.getStr("name_")+item.getStr("sub_name_"));
                });
            }

            setAttr("productList",productList);

            setAttr("record",record);
        }

        renderJsp("/page/shoporder/info.jsp");
    }
}
